package com.example.springmvc_demo2.service.impl;

import com.example.springmvc_demo2.entity.Student;
import com.example.springmvc_demo2.mapper.StudentMapper;
import com.example.springmvc_demo2.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Student> getAllStudents() {
        return studentMapper.findAllStudents();
    }

    @Override
    public Student getStudentById(Long id) {
        return studentMapper.findStudentById(id);
    }

    @Override
    public boolean addStudent(Student student) {
        // Check if studentId already exists
        if (studentMapper.findStudentByStudentId(student.getStudentId()) != null) {
            return false; // Student ID already exists
        }
        try {
            studentMapper.insertStudent(student);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateStudent(Student student) {
        // Check if the studentId already exists for another student (if studentId is being updated)
        Student existingStudent = studentMapper.findStudentByStudentId(student.getStudentId());
        if (existingStudent != null && !existingStudent.getId().equals(student.getId())) {
            return false; // Student ID already exists for another student
        }
        try {
            studentMapper.updateStudent(student);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteStudent(Long id) {
        try {
            studentMapper.deleteStudent(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
} 